package com.qidian.client;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;


/**
 * 从转发平台获取答案
 * 
 * */
public class ThreadGetAnswer extends Thread
{

	static Logger logger = Logger.getLogger(ThreadGetAnswer.class) ;
    protected boolean      isStopped    = false;
    protected Thread       runningThread= null;
    TransMessageBeanCache tMsgCache = TransMessageBeanCache.getInstance() ;
	public void run()
	{
        synchronized(this){
            this.runningThread = Thread.currentThread();
        }
        
        System.out.println(this.getClass().getName() + " start up") ;
        
		while(!isStopped)
		{
			if (tMsgCache.transedMsgBuf.size() > 0)
				System.out.println("Get answer size:"+tMsgCache.transedMsgBuf.size());
			
			ConcurrentHashMap<String,TransMessageBean> buf = tMsgCache.getTransedMsgBuf() ;
			
			Iterator<TransMessageBean> transMsgItr = buf.values().iterator() ;
			while(transMsgItr.hasNext())
			{
				// 遍历已转发消息
				TransMessageBean msg = transMsgItr.next() ;
				
				// 试图获取答案
				BaseTranser transer = msg.getTranser() ;
				String answer = transer.getAnswer(msg.getTid(), null) ;
				
				// 答案未准备好，继续
				if (transer.isNotReady(answer))
					continue ;
				else if (transer.isAnswer(answer))
				{// 正常答案，将消息移动至已回答队列
					msg.setAnswer(answer) ;
					buf.remove(msg.getId()) ;
					TransMessageBeanCache.getInstance().addAnswered(msg) ;
					continue ;
				} 
				else if (msg.isTimeout())
				{// 如果超时，丢弃
					buf.remove(msg.getId()) ;
					continue ;
				}
				
				// 其他错误，继续获取直至超时
				
			}
		
			try {
				Thread.sleep(500) ;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		logger.info("Get answer thread stopped!") ;
	}
}
